package com.xxlie.spring.service;

import com.xxlie.spring.common.Constants;
import com.xxlie.spring.common.UserContext;
import com.xxlie.spring.dao.UserDao;
import com.xxlie.spring.entity.User;
import com.xxlie.spring.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public User findById(Integer id){
        return userDao.findById(id);
    }

    public User findByAppid(String appid){
        return userDao.findByAppid(appid);
    }

    public Integer update(String appid){
        User user = new User();
        user.setId(UserContext.getCurrentUser().getId());
        user.setAppid(appid);
        return userDao.updateById(user);
    }

    public void deleteById(Integer id) {
        userDao.deleteById(id);
    }

    public User doRegister(String name, String passwd) {
        User userDb = userDao.findByName(name);
        if (userDb != null) {
            throw new BusinessException(Constants.LOGIN_NAME_HAS_EXIST);
        }
        User user = new User();
        user.setName(name);
        user.setPasswd(DigestUtils.md5Hex(passwd));
        userDao.addUser(user);
        user.setId(user.getId());
        return user;
    }

    public User doLogin(String name, String passwd) {
        User userDb = userDao.findByName(name);
        if (Objects.isNull(userDb)) {
            throw new BusinessException(Constants.LOGIN_NAME_IS_NOT_EXIST);
        }
        if (userDb.getPasswd().equals(DigestUtils.md5Hex(passwd))) {
            return userDb;
        } else {
            throw new BusinessException(Constants.LOGIN_NAME_NOT_MATCH_PASSWD);
        }
    }
}
